package com.lq.user.controller;

import com.lq.common.result.Result;
import com.lq.common.util.JwtUtil;
import com.lq.common.util.UserContext;
import com.lq.user.dto.PasswordChangeRequest;
import com.lq.user.entity.User;
import com.lq.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lq
 * @since 2025-08-23
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户管理", description = "用户相关接口")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "用户注册", notes = "注册新用户")
    @ApiResponses({
        @ApiResponse(code = 200, message = "注册成功"),
        @ApiResponse(code = 400, message = "请求参数错误"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PostMapping("/register")
    public Result register(@ApiParam(value = "注册信息", required = true) @RequestParam String username,
                           @RequestParam String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        boolean result = userService.register(user);
        if (result) {
            // 注册成功后清除密码信息再返回
            user.setPassword(null);
            return Result.success(user);
        } else {
            return Result.failed("注册失败");
        }
    }

    @ApiOperation(value = "用户登录", notes = "用户登录验证")
    @ApiResponses({
        @ApiResponse(code = 200, message = "登录成功"),
        @ApiResponse(code = 400, message = "用户名或密码错误"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PostMapping("/login")
    public Result login(@ApiParam(value = "登录信息", required = true)
                        @RequestParam String username,
                        @RequestParam String password) {
        boolean result = userService.login(username, password);
        if (result) {
            User user = userService.getByUsername(username);
            
            // 生成JWT Token
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user.getUsername());
            claims.put("id", user.getId());
            String token = JwtUtil.generateToken(claims);
            
            // 返回用户信息和Token
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("user", user);
            responseData.put("token", token);
            
            return Result.success(responseData);
        } else {
            return Result.failed("用户名或密码错误");
        }
    }

    @ApiOperation(value = "根据ID获取用户", notes = "根据用户ID获取用户详细信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @GetMapping("/{id}")
    public Result getUserById(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        System.out.println("   yonghu" + UserContext.getUserId());
        return Result.success(userService.getById(id));
    }

    @ApiOperation(value = "获取所有用户", notes = "获取系统中所有的用户")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @GetMapping("/")
    public Result getAllUsers() {
        return Result.success(userService.list());
    }

    @ApiOperation(value = "根据用户名获取用户", notes = "根据用户名获取用户信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @GetMapping("/username/{username}")
    public Result getUserByUsername(@ApiParam(value = "用户名", required = true) @PathVariable String username) {
        User user = userService.getByUsername(username);
        return Result.success(user);
    }

    @ApiOperation(value = "根据手机号获取用户", notes = "根据手机号获取用户信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @GetMapping("/phone/{phone}")
    public Result getUserByPhone(@ApiParam(value = "手机号", required = true) @PathVariable String phone) {
        User user = userService.getByPhone(phone);
        return Result.success(user);
    }

    @ApiOperation(value = "更新用户", notes = "根据用户ID更新用户信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "更新成功"),
        @ApiResponse(code = 400, message = "请求参数错误"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PutMapping("/{id}")
    public Result updateUser(@ApiParam(value = "用户ID", required = true) @PathVariable Long id,
                             @ApiParam(value = "用户信息", required = true) @RequestBody User user) {
        user.setId(id);
        userService.updateById(user);
        return Result.success(user);
    }

    @ApiOperation(value = "删除用户", notes = "根据用户ID删除用户")
    @ApiResponses({
        @ApiResponse(code = 200, message = "删除成功"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @DeleteMapping("/{id}")
    public Result deleteUser(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }

    @ApiOperation(value = "更新用户状态", notes = "根据用户ID更新用户状态")
    @ApiResponses({
        @ApiResponse(code = 200, message = "更新成功"),
        @ApiResponse(code = 400, message = "请求参数错误"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PutMapping("/{id}/status")
    public Result updateStatus(@ApiParam(value = "用户ID", required = true) @PathVariable Long id,
                               @ApiParam(value = "状态(0-禁用,1-正常)", required = true) @RequestParam Integer status) {
        boolean result = userService.updateStatus(id, status);
        if (result) {
            return Result.success();
        } else {
            return Result.failed("更新状态失败");
        }
    }

    @ApiOperation(value = "修改密码", notes = "根据用户ID修改密码")
    @ApiResponses({
        @ApiResponse(code = 200, message = "修改成功"),
        @ApiResponse(code = 400, message = "原密码错误"),
        @ApiResponse(code = 404, message = "用户不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PutMapping("/{id}/password")
    public Result changePassword(@ApiParam(value = "用户ID", required = true) @PathVariable Long id,
                                 @ApiParam(value = "密码信息", required = true) @RequestBody PasswordChangeRequest request) {
        boolean result = userService.changePassword(id, request.getOldPassword(), request.getNewPassword());
        if (result) {
            return Result.success();
        } else {
            return Result.failed("修改密码失败");
        }
    }

}